#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
QR文件编码器打包脚本
用于将Python程序打包为独立的exe文件
"""

import os
import sys
import subprocess
import shutil
from pathlib import Path

def build_exe():
    """打包程序为exe"""
    
    # 获取当前目录
    current_dir = Path.cwd()
    
    # 清理之前的构建
    dist_dir = current_dir / "dist"
    build_dir = current_dir / "build"
    
    if dist_dir.exists():
        shutil.rmtree(dist_dir)
    if build_dir.exists():
        shutil.rmtree(build_dir)
    
    # PyInstaller命令参数
    cmd = [
        "pyinstaller",
        "--name=QRFileCoder",
        "--windowed",  # 不显示控制台窗口
        "--onefile",   # 打包为单个exe文件
        "--clean",     # 清理临时文件
        "--noconfirm", # 自动确认
        "--icon=NONE",  # 可以添加图标文件
        "--hidden-import=PIL._tkinter_finder",  # 隐藏导入
        "--hidden-import=pyzbar.pyzbar",
        "--collect-all=Pillow",
        "--collect-all=qrcode",
        "--collect-all=pyzbar",
        "qr_file_coder.py"
    ]
    
    print("开始打包程序...")
    print("命令:", " ".join(cmd))
    
    try:
        # 执行打包命令
        result = subprocess.run(cmd, capture_output=True, text=True, cwd=current_dir)
        
        if result.returncode == 0:
            print("✅ 打包成功!")
            print(f"生成的exe文件位于: {current_dir / 'dist' / 'QRFileCoder.exe'}")
            
            # 创建启动脚本
            create_launcher_bat(current_dir)
            
        else:
            print("❌ 打包失败!")
            print("错误信息:")
            print(result.stderr)
            
    except Exception as e:
        print(f"打包过程中出现错误: {e}")

def create_launcher_bat(current_dir):
    """创建启动批处理文件"""
    bat_content = f"""@echo off
title QRFileCoder
cd /d "{current_dir}"
dist\\QRFileCoder.exe
pause
"""
    
    bat_file = current_dir / "run_exe.bat"
    with open(bat_file, "w", encoding="utf-8") as f:
        f.write(bat_content)
    
    print(f"启动脚本已创建: {bat_file}")

def install_requirements():
    """安装依赖包"""
    print("检查并安装依赖...")
    
    requirements = [
        "pyinstaller",
        "Pillow==10.0.0",
        "qrcode[pil]==7.4.2",
        "pyzbar==0.1.9"
    ]
    
    for package in requirements:
        try:
            subprocess.run([sys.executable, "-m", "pip", "install", package], 
                         check=True, capture_output=True)
            print(f"✅ 已安装: {package}")
        except subprocess.CalledProcessError as e:
            print(f"❌ 安装失败: {package} - {e}")

if __name__ == "__main__":
    print("QR文件编码器打包工具")
    print("=" * 50)
    
    # 安装依赖
    install_requirements()
    
    # 开始打包
    build_exe()
    
    print("\n打包完成！")
    print("使用方法:")
    print("1. 运行 run_exe.bat 启动程序")
    print("2. 或直接运行 dist\\QRFileCoder.exe")